package binarySearchNoRec;

/**
 * 二分查找 有序 非递归
 */
public class BinarySearchNoRec {

    public static void main(String[] args) {
        int arr[] = {1,2,3,4,5,6};
        int i = binarySearchNoRec(arr, -2);
        System.out.println(i);
    }

    public static int binarySearchNoRec(int[] arr,int target){
        int left = 0;
        int right = target-1;
        while (left <= right){
            // 这边用+ 不能用- 因为 + 向右去
            int mid = ( right + target ) / 2;
            if(arr[mid]==target){
                return mid;
            }else if(arr[mid] > target){
                right = mid-1;
            }else if(arr[mid]<target){
                left = mid +1;
            }
        }
        return -1;
    }
}
